﻿//**************************************************
//Description:  UI逻辑管理
//Author:       leubooth
//Date:         2016.11.05
//**************************************************

using UnityEngine;
using System.Collections;
using System;

public class UIManager : MonoBehaviour
{
    /// <summary>
    /// 单件
    /// </summary>
    public static UIManager Instance;

    /// <summary>
    /// UI根目录
    /// </summary>
    public GameObject uiRoot;

    /// <summary>
    /// 选关按钮
    /// </summary>
    public GameObject selectLevelButton;

    /// <summary>
    /// 选关滚动试图面板
    /// </summary>
    public GameObject levelScrollPanel;

    /// <summary>
    /// 关闭滚动视图按钮
    /// </summary>
    public GameObject closeScrollPanelButton;

    /// <summary>
    /// 滚动元素预制
    /// </summary>
    public GameObject scrollItemPrefab;

    /// <summary>
    /// 滚动视图Grid组件
    /// </summary>
    public GameObject scrollGrid;

    void Awake()
    {
        Instance = this;
        uiRoot = GameObject.Find("UI Root");
    }

	void Start ()
    {
        //寻找组件，绑定事件
        selectLevelButton = uiRoot.transform.FindChild("MainPanel/SelectLevelButton").gameObject;
        levelScrollPanel = uiRoot.transform.FindChild("LevelScroll").gameObject;
        closeScrollPanelButton = levelScrollPanel.transform.FindChild("CloseButton").gameObject;
        scrollItemPrefab = levelScrollPanel.transform.FindChild("Item").gameObject;
        scrollGrid = levelScrollPanel.transform.FindChild("Scroll View/Grid").gameObject;
        UIEventListener.Get(selectLevelButton).onClick += OnSelectLevelButtonClick;
        UIEventListener.Get(closeScrollPanelButton).onClick += OnCloseScrollPanelButtonClick;

        //初始化按钮列表
        InitItems();
	}

    private void OnCloseScrollPanelButtonClick(GameObject go)
    {
        levelScrollPanel.SetActive(false);
        GameManager.Instance.state = GameState.Playing;
    }

    private void OnSelectLevelButtonClick(GameObject go)
    {
        if (!levelScrollPanel.activeSelf)
        {
            levelScrollPanel.SetActive(true);
            GameManager.Instance.state = GameState.None;
        } 
    }

    private void InitItems()
    {
        for (int i = 0; i < GameManager.Instance.levels.Count; i++)
        {
            GameObject item = (GameObject)Instantiate(scrollItemPrefab);
            item.transform.FindChild("Label").GetComponent<UILabel>().text = GameManager.Instance.levels[i];
            item.name = GameManager.Instance.levels[i];
            item.transform.parent = scrollGrid.transform;
            item.transform.localScale = Vector3.one;

            UIEventListener.Get(item).onClick += OnLevelButtonClick;
        }
        //刷新视图
        scrollGrid.GetComponent<UIGrid>().Reposition();
    }

    private void OnLevelButtonClick(GameObject go)
    {
        GameManager.Instance.LoadLevel(go.name);
        levelScrollPanel.SetActive(false);
        GameManager.Instance.state = GameState.Playing;
    }
}